<script setup lang="ts">
import { onMounted, ref, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useMessage, NButton, NInput, NImage, NModal, NCard } from 'naive-ui';
import { LoginFrom } from '@/typings/user';
import { getConfigKey, getMpQrCode, getLoginType, authSystem } from '@/api/user';
import { useUserStore } from '@/store/modules/user';
import to from 'await-to-js';
import { useI18n } from 'vue-i18n';
import { useBasicLayout } from '@/hooks/useBasicLayout';
const { isMobile } = useBasicLayout();
const { t } = useI18n();

const userStore = useUserStore();
const router = useRouter();
const message = useMessage();
const user = ref<LoginFrom>(Object.create(null));

// 点击登录
let loginLoading = ref(false);
async function handleValidateButtonClick(e: MouseEvent) {
  e.preventDefault();
  const { username, password } = user.value;
  // if (!validateAccount(username)) {
  // 	message.error(t("login.accountFormatError"));
  // 	return;
  // }
  if (username && password) {
    loginLoading.value = true;
    const [err, res] = await to(userStore.userLogin(user.value));
    if (!err) {
      message.success(t('login.loginSuccess'));
      let data = { username: res.data.userInfo.userId };
      localStorage.setItem('userInfo', JSON.stringify(data));
      await router.push('/');
      loginLoading.value = false;
    } else {
      message.error(err.message);
      loginLoading.value = false;
    }
  } else {
    message.error(t('login.usernameOrPasswordEmpty'));
  }
}

function validateAccount(account: string) {
  if (!account) {
    return false;
  }
  const phoneRegex = /^1[3456789]\d{9}$/;
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(account) || phoneRegex.test(account);
}

const handleRegistBtnClick = async (e: MouseEvent) => {
  router.push('/regist');
};

const copyright = ref('');

const logo = ref('');

const activate = ref(false);

const code = ref('');

// 在组件挂载后执行异步操作
onMounted(async () => {
  const [err, res] = await to(getConfigKey('copyright'));
  if (err) {
    console.error('获取配置失败', err.message);
  } else {
    copyright.value = res.msg;
  }
});

const activeTab = ref('login');

const showModal = ref(false);

// 登录二维码
const qrCode = ref('');
const ticket = ref('');

let intervalId: string | number | NodeJS.Timer | undefined;
// 定义轮询间隔时间，例如每3秒轮询一次
const POLLING_INTERVAL = 3000;

async function handleWxLogin() {
  showModal.value = true;
  //获取二维码信息
  const [err1, res1] = await to(getMpQrCode());
  if (err1) {
    message.error('获取二维码失败: ' + err1.message);
  } else {
    qrCode.value = res1.data.qrCodeUrl;
    ticket.value = res1.data.ticket;
    intervalId = setInterval(slectLoginType, POLLING_INTERVAL);
  }
}

// 1. 定时查询是否登录成功
async function slectLoginType() {
  const [err, res] = await to(getLoginType(ticket.value));
  if (!err) {
    console.log('res.token', res);
    if (res.data.token) {
      // 2. 登录成功,保存token
      userStore.userQrLogin(res.data.token);
      clearInterval(intervalId);
      // 3. 跳转到主页
      message.success(t('login.loginSuccess'));
      await router.push('/');
    }
  }
}

onUnmounted(() => {
  // 页面组件卸载前清除定时器，避免内存泄漏
  if (intervalId !== undefined) {
    clearInterval(intervalId);
  }
});

// 动态品牌内容
const brandTitle = ref('AI CRM');
const brandWelcome = ref('欢迎回来！');
const brandDesc = ref('智能沟通 · 高效协作');
const brandIcons = ref([
  `<svg class='icon-svg' viewBox='0 0 24 24'><circle cx='12' cy='12' r='10' fill='#b3e0ff' opacity='0.3'/><path d='M12 6v6l4 2' stroke='#5a7cff' stroke-width='2' fill='none'/></svg>`,
  `<svg class='icon-svg' viewBox='0 0 24 24'><rect x='4' y='4' width='16' height='16' rx='4' fill='#5a7cff' opacity='0.15'/><path d='M8 12h8M12 8v8' stroke='#5a7cff' stroke-width='2' fill='none'/></svg>`
]);
const brandIllustration = ref(`
  <svg width='120' height='80' viewBox='0 0 120 80'><ellipse cx='60' cy='70' rx='50' ry='10' fill='#eaf3fa'/><circle cx='60' cy='40' r='28' fill='#b3e0ff' opacity='0.18'/><circle cx='60' cy='40' r='18' fill='#5a7cff' opacity='0.12'/></svg>
`);

// 动画光点粒子数据
const particles = ref([
  // 随机生成20个粒子，位置、大小、颜色、动画延迟不同
  ...Array.from({ length: 20 }).map((_, i) => {
    const top = Math.random() * 90 + '%';
    const left = Math.random() * 90 + '%';
    const size = Math.random() * 10 + 8;
    const colors = ['#b3e0ff', '#5a7cff', '#00c6ff', '#fff'];
    const color = colors[Math.floor(Math.random() * colors.length)];
    const opacity = 0.18 + Math.random() * 0.18;
    const duration = 4 + Math.random() * 6;
    const delay = Math.random() * 4;
    return {
      style: {
        top,
        left,
        width: size + 'px',
        height: size + 'px',
        background: color,
        opacity,
        animationDuration: duration + 's',
        animationDelay: delay + 's'
      }
    };
  })
]);
</script>

<template>
  <div class="login-bg2">
    <!-- 动画光点背景层 -->
    <div class="bg-particles">
      <span v-for="(dot, idx) in particles" :key="idx" class="particle" :style="dot.style"></span>
    </div>
    <div class="login-card2 animate-card-in">
      <!-- 左侧品牌区 -->
      <div class="login-side">
        <div class="brand-title">{{ brandTitle }}</div>
        <div class="brand-welcome">{{ brandWelcome }}</div>
        <div class="brand-desc">{{ brandDesc }}</div>
        <div class="brand-icons">
          <span v-for="(icon, idx) in brandIcons" :key="idx" class="icon-svg" v-html="icon"></span>
        </div>
        <div class="brand-illus" v-html="brandIllustration"></div>
        <div class="brand-subtitle">让AI助力你的每一天</div>
        <div class="brand-features">
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" fill="#5a7cff" opacity="0.13" />
              <path d="M8 12l2 2 4-4" stroke="#5a7cff" stroke-width="2" fill="none" />
            </svg>
            <span>安全保障</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24">
              <rect x="4" y="4" width="16" height="16" rx="4" fill="#00c6ff" opacity="0.13" />
              <path d="M8 12h8" stroke="#00c6ff" stroke-width="2" fill="none" />
            </svg>
            <span>极速体验</span>
          </div>
          <div class="feature-item">
            <svg width="20" height="20" viewBox="0 0 24 24">
              <ellipse cx="12" cy="12" rx="8" ry="10" fill="#b3e0ff" opacity="0.13" />
              <path d="M8 12h8" stroke="#5a7cff" stroke-width="2" fill="none" />
            </svg>
            <span>云端同步</span>
          </div>
        </div>
        <div class="brand-trust">安全加密传输，数据隐私有保障</div>
      </div>
      <!-- 右侧表单区 -->
      <div class="login-main">
        <div class="login-title2">欢迎回来</div>
        <div class="login-sub2">请输入账号密码登录</div>
        <form class="login-form2">
          <div class="form-group2">
            <div class="input-wrap">
              <span class="input-icon">
                <svg width="20" height="20" viewBox="0 0 24 24">
                  <circle cx="12" cy="8" r="4" fill="#b3e0ff" />
                  <path d="M4 20c0-4 8-4 8-4s8 0 8 4" stroke="#5a7cff" stroke-width="2" fill="none" />
                </svg>
              </span>
              <input
                id="email"
                v-model="user.username"
                maxlength="32"
                :placeholder="$t('login.enterEmailOrPhone')"
                name="email"
                type="text"
                autocomplete="email"
                required
                class="form-input2"
              />
            </div>
          </div>
          <div class="form-group2">
            <div class="input-wrap">
              <span class="input-icon">
                <svg width="20" height="20" viewBox="0 0 24 24">
                  <rect x="6" y="10" width="12" height="8" rx="2" fill="#b3e0ff" />
                  <path d="M12 14v2" stroke="#5a7cff" stroke-width="2" />
                </svg>
              </span>
              <input
                id="password"
                maxLength="16"
                v-model="user.password"
                :placeholder="$t('login.enterPassword')"
                name="password"
                type="password"
                required
                class="form-input2"
              />
            </div>
          </div>
          <div class="form-row2">
            <!-- <a href="#/resetpassword" class="forgot-link2">
              <svg width="16" height="16" viewBox="0 0 24 24"><path d="M12 4v16m8-8H4" stroke="#5a7cff" stroke-width="2" fill="none" /></svg>
              忘记密码？
            </a> -->
          </div>
          <button type="button" class="login-btn2 animate-btn-glow2" @click="handleValidateButtonClick" :disabled="loginLoading">
            <template v-if="loginLoading">
              <svg class="loading-spin" width="22" height="22" viewBox="0 0 50 50">
                <circle class="path" cx="25" cy="25" r="20" fill="none" stroke="#fff" stroke-width="5" />
              </svg>
              登录中...
            </template>
            <template v-else>
              <!-- <svg width="20" height="20" viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7" stroke="#fff" stroke-width="2" fill="none" /></svg> -->
              登录
            </template>
          </button>
        </form>
        <!-- <div class="login-bottom2">
          <span>没有账号？</span>
          <a class="login-link2" @click="handleRegistBtnClick">
            <svg width="16" height="16" viewBox="0 0 24 24"><path d="M12 5v14m7-7H5" stroke="#0084ff" stroke-width="2" fill="none" /></svg>
            去注册
          </a>
        </div> -->
      </div>
    </div>
    <div class="footer2">
      <a target="_blank" href="https://beian.miit.gov.cn/">Copyright © 2025 西安友盟智能科技 版权所有 ICP备案号：陕ICP备2022001341号</a>
    </div>
  </div>
</template>

<style scoped>
.login-bg2 {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #fafdff 0%, #eaf3fa 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}
.bg-particles {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  z-index: 0;
}
.particle {
  position: absolute;
  border-radius: 50%;
  filter: blur(1.5px);
  animation: floatDot 8s linear infinite alternate;
}
@keyframes floatDot {
  0% {
    transform: translateY(0) scale(1);
    opacity: 0.7;
  }
  50% {
    transform: translateY(-30px) scale(1.15);
    opacity: 1;
  }
  100% {
    transform: translateY(0) scale(1);
    opacity: 0.7;
  }
}
.login-card2 {
  width: 820px;
  min-height: 440px;
  background: rgba(255, 255, 255, 0.92);
  border-radius: 32px;
  box-shadow: 0 8px 40px 0 rgba(0, 0, 0, 0.1), 0 0 0 3px #b3e0ff33;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  margin-top: 60px;
  margin-bottom: 32px;
  position: relative;
  backdrop-filter: blur(18px);
  border: 1.5px solid #d6eaff;
  animation: cardIn 0.9s cubic-bezier(0.23, 1.02, 0.32, 1) 0s 1;
  transition: box-shadow 0.3s, transform 0.3s;
}
/* .login-card2:hover {
  box-shadow: 0 16px 48px 0 rgba(90, 124, 255, 0.13), 0 0 0 6px #b3e0ff55;
  transform: translateY(-6px) scale(1.015);
} */
@keyframes cardIn {
  0% {
    opacity: 0;
    transform: translateY(40px) scale(0.98);
    filter: blur(6px);
  }
  60% {
    opacity: 1;
    transform: translateY(-8px) scale(1.03);
    filter: blur(0px);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
    filter: blur(0px);
  }
}
.login-side {
  flex: 1.1;
  background: linear-gradient(120deg, #eaf4ff 60%, #fafdff 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 36px 18px 36px 36px;
  border-right: 1.5px solid #e3e8ee;
  position: relative;
}
.brand-logo-wrap {
  margin-bottom: 18px;
}
.brand-logo {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  object-fit: cover;
}
.brand-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #5a7cff;
  margin-bottom: 8px;
  letter-spacing: 1px;
}
.brand-welcome {
  font-size: 1.18rem;
  color: #1a2340;
  font-weight: 600;
  margin-bottom: 4px;
}
.brand-desc {
  color: #6b7280;
  font-size: 1rem;
  margin-bottom: 18px;
}
.brand-icons {
  display: flex;
  gap: 12px;
  margin-bottom: 18px;
}
.icon-svg {
  width: 32px;
  height: 32px;
  display: inline-block;
}
.brand-illus {
  margin-top: 18px;
}
.login-main {
  flex: 1.3;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 36px 36px 18px;
}
.login-title2 {
  color: #1a2340;
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 8px;
  text-align: left;
  letter-spacing: 1px;
}
.login-sub2 {
  color: #6b7280;
  font-size: 1.08rem;
  margin-bottom: 24px;
  text-align: left;
}
.login-form2 {
  width: 100%;
  max-width: 320px;
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.form-group2 {
  width: 100%;
}
.input-wrap {
  display: flex;
  align-items: center;
  background: #fafdff;
  border: 1.5px solid #d1d5db;
  border-radius: 16px;
  padding: 0 10px;
  transition: border 0.2s, box-shadow 0.2s, background 0.2s;
}
.input-icon {
  margin-right: 6px;
  display: flex;
  align-items: center;
  color: #5a7cff;
}
.form-input2 {
  flex: 1;
  background: transparent;
  color: #1a2340;
  border: none;
  outline: none;
  font-size: 1.08rem;
  padding: 8px 0;
}
.input-wrap:focus-within {
  border-color: #5a7cff;
  background: #eaf4ff;
  box-shadow: 0 0 8px 0 #7ec3ff44, 0 0 0 2px #b3e0ff44;
}
.form-row2 {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 2px;
}
.forgot-link2 {
  color: #7ec3ff;
  font-size: 0.98rem;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 2px;
  transition: color 0.2s;
}
.forgot-link2:hover {
  color: #00c6ff;
}
.login-btn2 {
  width: 100%;
  background: linear-gradient(90deg, #5a7cff 0%, #b3e0ff 100%);
  color: #fff;
  font-weight: 600;
  border-radius: 16px;
  font-size: 1.13rem;
  padding: 13px 0;
  box-shadow: 0 2px 12px rgba(90, 124, 255, 0.09);
  margin-top: 8px;
  transition: box-shadow 0.2s, transform 0.2s, filter 0.2s;
  filter: drop-shadow(0 2px 8px rgba(90, 124, 255, 0.08));
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border: none;
  cursor: pointer;
}
.animate-btn-glow2 {
  position: relative;
  overflow: hidden;
  z-index: 1;
}
.animate-btn-glow2::before {
  content: '';
  position: absolute;
  left: -60%;
  top: 0;
  width: 60%;
  height: 100%;
  background: linear-gradient(120deg, transparent 0%, #fff8 50%, transparent 100%);
  transform: skewX(-24deg);
  opacity: 0.7;
  transition: opacity 0.2s;
  pointer-events: none;
}
.animate-btn-glow2:hover::before {
  animation: btnShine 1.1s linear;
}
@keyframes btnShine {
  0% {
    left: -60%;
    opacity: 0.2;
  }
  40% {
    left: 40%;
    opacity: 0.7;
  }
  100% {
    left: 110%;
    opacity: 0;
  }
}
.login-btn2:hover {
  box-shadow: 0 4px 18px rgba(90, 124, 255, 0.13);
  transform: translateY(-2px) scale(1.04);
  filter: brightness(1.08);
}
.login-bottom2 {
  margin-top: 18px;
  color: #6b7280;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 6px;
}
.login-link2 {
  color: #0084ff;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 2px;
  transition: color 0.2s;
}
.login-link2:hover {
  color: #00c6ff;
}
.footer2 {
  color: #999;
  font-size: 14px;
  text-align: center;
  margin-top: 0;
  z-index: 2;
}
.brand-subtitle {
  color: #5a7cff;
  font-size: 1.02rem;
  margin-top: 18px;
  margin-bottom: 8px;
  text-align: center;
  font-weight: 500;
  letter-spacing: 0.5px;
}
.brand-features {
  display: flex;
  gap: 18px;
  margin-top: 8px;
  margin-bottom: 8px;
  justify-content: center;
}
.feature-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 0.98rem;
}
.brand-trust {
  color: #b3e0ff;
  font-size: 0.95rem;
  margin-top: 8px;
  text-align: center;
}
.login-agree,
.login-social {
  display: none !important;
}
@media (max-width: 900px) {
  .login-card2 {
    flex-direction: column;
    width: 98vw;
    min-width: 0;
    padding: 0;
  }
  .login-side,
  .login-main {
    padding: 32px 8vw;
    border: none;
  }
  .login-side {
    border-bottom: 1.5px solid #e3e8ee;
    border-right: none;
  }
}
@media (max-width: 600px) {
  .login-card2 {
    padding: 0;
    min-width: 0;
    width: 100vw;
    border-radius: 0;
  }
  .login-side,
  .login-main {
    padding: 24px 4vw;
  }
  .login-title2 {
    font-size: 1.3rem;
  }
}
.loading-spin {
  animation: spin 1s linear infinite;
  margin-right: 8px;
  vertical-align: middle;
}
@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}
.form-input2::placeholder {
  font-size: 0.92rem;
  color: #b0b3b8;
  opacity: 1;
}
</style>
